//用于实现多线程的封装
#pragma once

#include <iostream>
#include <pthread.h>
#include <string>
#include <unistd.h>

class Thread
{
public:
    typedef enum
    {
        NEW = 0,
        RUNNING,
        EXITED
    } ThreadStatus; // 创建一个线程状态枚举变量

    typedef void (*func_t)(void *);

public:
    Thread(int num, func_t func, void *args)
        : _tid(0), _status(NEW), _func(func), _args(args)
    {
        char name[128];
        snprintf(name, sizeof(name), "thread-%d", num);
        _name = name;
    }
    ~Thread()
    {
    }
    // 是类的成员函数，类的成员函数具有默认参数this
    static void *runHelper(void *args)
    {
        //_func(_args);static成员函数无法访问类内属性
        Thread *ts = (Thread *)args;
        (*ts)();
        return nullptr;
    }
    void operator()() // 仿函数
    {
        if (_func != nullptr)
            _func(_args); // 回调实现
    }

    void run()
    {
        int n = pthread_create(&_tid, nullptr, runHelper, this);
        if (n != 0)
            exit(1);
        _status = RUNNING;
    }

    void join()
    {
        int n = pthread_join(_tid, nullptr);
        if (n != 0)
        {
            std::cerr << "main thread join thread" << _name << "error" << std::endl;
        }
        _status = EXITED;
    }

    int status() { return _status; }

    std::string threadname() { return _name; }

    pthread_t threadid()
    {
        if (_status == RUNNING)
        {
            return _tid;
        }
        else
        {
            std::cout << "thread is not running" << std::endl;
            return 0;
        }
    }

private:
    pthread_t _tid;
    std::string _name;
    func_t _func; // 线程未来要执行的回调函数
    ThreadStatus _status;
    void *_args;
};